package com.jcli._定时提醒;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class FocusAssistantApp01 {
    private static final int ONE_MINUTE = 60 * 1000; // 1分钟的毫秒数
    private static final int FOCUS_TIME = 2000; // 20分钟的毫秒数
    // private static final int FOCUS_TIME = 20 * ONE_MINUTE; // 20分钟的毫秒数

    private static Timer timer;

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> createAndShowGUI());
    }

    private static void createAndShowGUI() {
        JFrame frame = new JFrame("专注助手");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JPanel panel = new JPanel();
        JButton startButton = new JButton("开始专注计时器");
        JButton stopButton = new JButton("停止专注计时器");

        startButton.addActionListener(e -> startFocusTimer());
        stopButton.addActionListener(e -> stopFocusTimer());

        panel.add(startButton);
        panel.add(stopButton);

        frame.getContentPane().add(panel, BorderLayout.CENTER);
        frame.setSize(300, 200);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    private static void startFocusTimer() {
        stopFocusTimer(); // 如果有正在运行的计时器，先停止

        timer = new Timer(FOCUS_TIME, new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                showNotification();
            }
        });

        timer.setRepeats(false); // 设置为false，只运行一次
        timer.start();
    }

    private static void stopFocusTimer() {
        if (timer != null && timer.isRunning()) {
            timer.stop();
        }
    }

    private static void showNotification() {
        if (SystemTray.isSupported()) {
            try {
                SystemTray tray = SystemTray.getSystemTray();

                // 加载托盘图标（根据实际路径调整）
                Image image = Toolkit.getDefaultToolkit().getImage("pic/akx.png");

                // 创建弹出菜单
                PopupMenu popupMenu = new PopupMenu();
                MenuItem exitItem = new MenuItem("退出");
                exitItem.addActionListener(e -> System.exit(0));
                popupMenu.add(exitItem);

                // 创建托盘图标
                TrayIcon trayIcon = new TrayIcon(image, "专注助手", popupMenu);
                trayIcon.setImageAutoSize(true);

                // 将托盘图标添加到系统托盘
                tray.add(trayIcon);

                // 在通知中显示消息
                trayIcon.displayMessage("休息一下！", "您已完成专注时间。", TrayIcon.MessageType.INFO);
            } catch (AWTException ex) {
                ex.printStackTrace();
            }
        } else {
            System.out.println("不支持系统托盘");
        }
    }
}
